package org.forum.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.forum.controller.Interface.PAGES;
import org.forum.controller.interceptor.DemographicStatistics;
import org.forum.domain.User;
import org.forum.service.UserInfoService;
import org.forum.service.UserService;
import org.forum.utils.JsonUtil;
import org.forum.utils.PersistenceUtil;
import org.forum.utils.SecurityCodeUtil;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.forum.domain.Forum;
import org.forum.domain.Icon;

/**
 * 提供如下功能：
 * 1、跳转到注册页面
 * 2、注册
 * 3、跳转到个人中心
 * 4、产生注册验证码并返回验证码
 * 5、ajax异步检验验证码是否正确
 * 10、用户图标上传
 * 11、返回用户所关注的所有论坛
 * @author One
 *
 */
public class UserInfoController {
	
	public static final String SECURITYCODE_WRONG = "securitycode_wrong";
	
	public static final String SECURITYCODE_RIGHT = "securitycode_right";
	
	public static final String PASSWORD_WRONG ="password_wrong";
	
	public static final String ACCOUNT_ALREADY_EXIST = "account_already_exist";
	
	//Spring注入对象
	Logger logger = LoggerFactory.getLogger(UserInfoController.class);
	
	private JsonUtil jsonUtil;

	public void setJsonUtil(JsonUtil jsonUtil) {
		this.jsonUtil = jsonUtil;
	}
	
	private UserInfoService userInfoService;

	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}
	
	PersistenceUtil persistenceUtil;

	public void setPersistenceUtil(PersistenceUtil persistenceUtil) {
		this.persistenceUtil = persistenceUtil;
	}

	private String iconPersistenceUrl;

	public void setIconPersistenceUrl(String iconPersistenceUrl) {
		this.iconPersistenceUrl = iconPersistenceUrl;
	}

	//注入生成验证码的对象
	private SecurityCodeUtil securityCodeUtil;

	public void setSecurityCodeUtil(SecurityCodeUtil securityCodeUtil) {
		this.securityCodeUtil = securityCodeUtil;
	}

	//struts注入的相关数据
	private User user;
	
	public User getUser() {
		logger.debug("#####getUser#####");
		return user;
	}

	public void setUser(User user){
		logger.debug("######setUser######");
		this.user = user;
	}

	private String registerSecurityCode;
	
	public void setRegisterSecurityCode(String registerSecurityCode) {
		this.registerSecurityCode = registerSecurityCode;
	}

	private File icon;
	
	public File getIcon() {
		if(logger.isDebugEnabled()){
			logger.debug("############getIcon###########");
		}
		return icon;
	}

	public void setIcon(File icon) {
		if(logger.isDebugEnabled()){
			logger.debug("############setIcon###########");
		}
		this.icon = icon;
	}
	
	private String iconContentType;

	public void setIconContentType(String iconContentType) {
		this.iconContentType = iconContentType;
	}
	
	private String iconFileName;

	public void setIconFileName(String iconFileName) {
		this.iconFileName = iconFileName;
	}

	/**
	 * @pass_Test
	 * 跳转到注册页面
	 * @return
	 */
	public String registerPage(){
		return PAGES.REGISTERPAGE;
	}
	
	
	/**
	 * @pass_Test 
	 * 1、验证码错误
	 * 2、验证码正确
	 * 3、账号已存在
	 * 4、账号存在
	 *@problem
	 *1、hibernate没有进行唯一性约束
	 * 注册账户
	 * @return
	 */
	public String register(){
		
		String securityCode = (String)ServletActionContext.getRequest()
				.getSession().getAttribute("SecurityCode");
		JSONObject jsonObject = new JSONObject();		
		//检验验证码
		if(!securityCode.equalsIgnoreCase(registerSecurityCode)){
			if(logger.isDebugEnabled()){
				logger.debug("security code wrong!" + "\n" + user.toString());
			}
			jsonObject.put("verification_result", SECURITYCODE_WRONG);
			jsonUtil.outToJsonString(jsonObject.toString());
			return null;
		}
		//检查账号是否已经注册,如果账号存在则进入
		if(userInfoService.isAccountAlreadyExist(user)){
			if(logger.isDebugEnabled()){
				logger.debug("account already exist!" + "\n" + user.toString());
			}
			jsonObject.put("verfication_result", ACCOUNT_ALREADY_EXIST);
			jsonUtil.outToJsonString(jsonObject.toString());
			return null;
		}
		//持久化用户数据信息
		userInfoService.saveUser(user);
		
		//注册成功,将个人信息存放在servlet session中，并且跳转至个人中心
		ServletActionContext.getRequest().getSession().setAttribute("user", user);
		return PAGES.HOMEPAGE;
	}


	/**
	 * @pass_Test
	 * 跳转至个人中心
	 * @return
	 */
	public String personalCenter(){
		return PAGES.PERSONALCENTER;
	}
	

	/**
	 * @pass_Test
	 * 生成注册验证码
	 */
	public void registerSecurityCode(){
		try {
			securityCodeUtil.generateSecurityCode();
		} catch (Exception e) {
			if(logger.isDebugEnabled()){
				logger.debug("产生登陆验证码错误" + "\n" + e.getMessage());
			}
		}
	}
	
	/**
	 * ajax异步判断验证码是否正确
	 * 如果正确，则返回json对象(返回数据在输出流中)
	 * 如果错误，则返回json对象(返回数据在输出流中)
	 * @return
	 */
	public void isSecurityCodeRight(){
		String securityCode = (String)ServletActionContext.getRequest()
				.getSession().getAttribute("SecurityCode");
		JSONObject result = new JSONObject();
		if(null != securityCode || registerSecurityCode != securityCode ){
			result.put("verification_result", SECURITYCODE_WRONG);
		}
		result.put("verification_result", SECURITYCODE_RIGHT);
		jsonUtil.outToJsonString(result.toString());
	}
	
	/**
	 * @pass_Test
	 * 设置用户图标
	 * 1、获取存储地址
	 * 2、持久化Icon关联
	 * 3、持久化图片
	 */
	public void uploadUserIcon(){
		//持久化Icon关联
		Icon icon = new Icon();

		//地址有问题
		icon.setUrl(getPersistenceUri());
		int iconId = (int)userInfoService.saveIcon(icon);
		if(logger.isDebugEnabled()){
			logger.debug("iconId=" + iconId);
		}
		icon.setIconId(iconId);
		//
		User user = (User)ServletActionContext.getRequest().getSession().getAttribute("user");
		user.setIcon(icon);
		userInfoService.updateUser(user);
		List<File> icons = new ArrayList<>();
		icons.add(this.icon);
		//持久化图片
		persistenceUtil.persistPicture(icons, getPersistenceUri());
	}
	
	/**
	 * @pass_Test
	 * 获取完全的文件存储uri
	 * @return
	 */
	private String getPersistenceUri(){
		String webContextPath = ServletActionContext.getServletContext()
				.getRealPath(iconPersistenceUrl);
		String uuid = UUID.randomUUID().toString();
		if(logger.isDebugEnabled()){
			logger.debug("iconContentType:" + iconContentType);
		}
		String suffix =  iconContentType.substring(iconContentType.lastIndexOf('/') + 1);
		if(logger.isDebugEnabled()){
			logger.debug("suffix:" + suffix);
		}
		
		if(logger.isDebugEnabled()){
			logger.debug(webContextPath + File.separatorChar +  uuid + "." + suffix);
		}
		return webContextPath +File.separator +  uuid + "." + suffix;
	}
	
	/**
	 * 得到用户关注的所有论坛并以json数据的形式返回
	 */
	public void getFollowedForums(){
		ServletActionContext.getRequest().getSession().getAttribute("user");
		Set<Forum> forums =   user.getForums();
		JSONObject jsonObject = new JSONObject();
		Iterator iter = forums.iterator();
		Forum forum = null;
		while(iter.hasNext()){
			forum = (Forum) iter.next();
			jsonObject.put(forum.getTitle(), forum);
		}
		jsonUtil.outToJsonString(jsonObject.toString());
	}
}
